// 统一的API客户端配置
import axios from 'axios'
import { API_CONFIG } from './constants'

// 创建axios实例
export const apiClient = axios.create({
  baseURL: API_CONFIG.BASE_URL.replace('/api', ''), // 移除/api后缀，因为路由中会添加
  timeout: API_CONFIG.TIMEOUT,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器 - 添加认证token
apiClient.interceptors.request.use(
  (config) => {
    // 直接从localStorage获取token，避免在拦截器中使用store
    const token = localStorage.getItem('auth_token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器 - 处理错误
apiClient.interceptors.response.use(
  (response) => {
    return response
  },
  (error) => {
    if (error.response?.status === 401) {
      // token过期或无效，清除认证信息并跳转到登录页
      localStorage.removeItem('auth_user')
      localStorage.removeItem('auth_token')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

// 通用请求函数（用于fetch API）
export async function request<T>(url: string, options: RequestInit = {}): Promise<T> {
  // 获取存储的token
  const token = localStorage.getItem('auth_token')
  
  const response = await fetch(`${API_CONFIG.BASE_URL}${url}`, {
    headers: {
      'Content-Type': 'application/json',
      ...(token && { 'Authorization': `Bearer ${token}` }),
      ...options.headers,
    },
    ...options,
  })

  if (!response.ok) {
    let errorMessage = `HTTP error! status: ${response.status}`
    try {
      const errorData = await response.json()
      if (errorData.message) {
        errorMessage = errorData.message
      }
    } catch {
      // 如果无法解析错误响应，使用默认错误消息
    }
    
    // 处理401错误
    if (response.status === 401) {
      localStorage.removeItem('auth_user')
      localStorage.removeItem('auth_token')
      window.location.href = '/login'
    }
    
    throw new Error(errorMessage)
  }

  const responseData = await response.json()
  return responseData
}

export default apiClient